package com.bls.cate.ui.activity.person_info_change;

import android.content.Intent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.bls.blslib.eventbus.Event;
import com.bls.blslib.eventbus.EventBusUtils;
import com.bls.cate.R;
import com.bls.cate.constant.EventBusCode;
import com.bls.cate.constant.Interface;
import com.bls.cate.model.LoginSpRes;
import com.bls.cate.model.RootRes;
import com.bls.cate.ui.widget.TitleView;
import com.bls.cate.utils.AccountUtil;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 　　  () 　　　  ()
 * 　　  ( ) 　　　( )
 * 　　  ( ) 　　　( )
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　┻　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ——————————————————
 * Created by BinglingSu on 2018/2/3.
 */

public class PersonInfoChangeActivity extends BaseActivity implements TitleView.OnTitleClickListener, RadioGroup.OnCheckedChangeListener, DatePicker.OnDateChangedListener {

    private PersonInfoChangeActivity mActivity;
    private String uniqueId;
    private String type;
    private String nickName = "扉页";
    private int sex = 2;
    private String strBirthday;

    private TitleView titleView;
    private RelativeLayout rlNickName, rlBirthday;
    private EditText etNickName;
    private RadioGroup rgSex;
    private RadioButton rbSexMale, rbSexFemale, rbSexNone;
    private TextView tvBirthday;
    private DatePicker dpBirthday;


    //private String[] strIntentBirthdays;


    @Override
    protected void initParams() {
        super.initParams();
        mActivity = (PersonInfoChangeActivity) getActivity();
        Intent intent = getIntent();
        uniqueId = intent.getStringExtra("UniqueId");
        type = intent.getStringExtra("Type");
        if (StringUtils.equals(type, "NickName")) {
            nickName = intent.getStringExtra("Value");
        } else if (StringUtils.equals(type, "Sex")) {
            sex = intent.getIntExtra("Value", 2);
        } else if (StringUtils.equals(type, "Birthday")) {
            strBirthday = intent.getStringExtra("Value");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person_info_change;
    }

    @Override
    protected void initFvb() {
        titleView = findViewById(R.id.title_view);
        rlNickName = findViewById(R.id.rl_nickname);
        etNickName = findViewById(R.id.et_nickname);
        rgSex = findViewById(R.id.rg_sex);
        rbSexMale = findViewById(R.id.rb_sex_male);
        rbSexFemale = findViewById(R.id.rb_sex_female);
        rbSexNone = findViewById(R.id.rb_sex_none);
        rlBirthday = findViewById(R.id.rl_birthday);
        tvBirthday = findViewById(R.id.tv_birthday);
        dpBirthday = findViewById(R.id.dp_birthday);
    }

    @Override
    protected void initView() {
        titleView.setBtnMode(2, 2);
        titleView.titleRightTv.setText("保存");
        if (StringUtils.equals(type, "NickName")) {
            titleView.setTitleMiddleText("昵称");
            rlNickName.setVisibility(View.VISIBLE);
            etNickName.setHint(nickName);
        } else if (StringUtils.equals(type, "Sex")) {
            titleView.setTitleMiddleText("性别");
            rgSex.setVisibility(View.VISIBLE);
            rgSex.check(sex == 0 ? rbSexMale.getId() : (sex == 1 ? rbSexFemale.getId() : rbSexNone.getId()));
        } else if (StringUtils.equals(type, "Birthday")) {
            titleView.setTitleMiddleText("生日");
            rlBirthday.setVisibility(View.VISIBLE);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

            Date nowDate = TimeUtils.getNowDate();
            String strNowDate = dateFormat.format(nowDate);
            String[] strBirthdayArray;
            if (strBirthday.length() > 0) {
                tvBirthday.setText(strBirthday);
                strBirthdayArray = strBirthday.split("-");
            } else {
                tvBirthday.setText(strNowDate);
                strBirthdayArray = strNowDate.split("-");
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(TimeUtils.getNowDate());
            int minYear = calendar.get(Calendar.YEAR) - 150;
            String strMinBirth = minYear + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
            Date minBirth = TimeUtils.string2Date(strMinBirth, dateFormat);
            dpBirthday.setMinDate(TimeUtils.date2Millis(minBirth));
            dpBirthday.setMaxDate(TimeUtils.getNowMills());
            dpBirthday.init(Integer.parseInt(strBirthdayArray[0]), Integer.parseInt(strBirthdayArray[1]) - 1, Integer.parseInt(strBirthdayArray[2]), this);

        }
    }

    @Override
    protected void initListener() {
        titleView.setTitleClickListener(this);
        rgSex.setOnCheckedChangeListener(this);
    }

    @Override
    public void onTitleClick(int btnType) {
        if (btnType == 2) {
            mActivity.finish();
        } else if (btnType == 4 && StringUtils.equals(type, "NickName")) {
            btnEventChangeNickName();
        } else if (btnType == 4 && StringUtils.equals(type, "Sex")) {
            btnEventChangeSex();
        } else if (btnType == 4 && StringUtils.equals(type, "Birthday")) {
            btnEventChangeBirthday();
        }
    }

    /**
     * 修改生日
     */
    private void btnEventChangeBirthday() {
        presenter.requestStrData(Interface.INTERFACE_CODE_Update_Birth, Interface.INTERFACE_USERINFO, CacheMode.NO_CACHE,
                new HttpParams("RequestMethod", "Birthday"),
                new HttpParams("UniqueId", uniqueId),
                new HttpParams("Birthday", strBirthday));
    }

    /**
     * 修改昵称
     */
    private void btnEventChangeNickName() {
        String tempNickName = etNickName.getText().toString().trim();
        if (tempNickName.length() < 1 || tempNickName.length() > 10) {
            ToastUtils.showShort(R.string.change_nickname_length);
        } else {
            presenter.requestStrData(Interface.INTERFACE_CODE_Update_NickName, Interface.INTERFACE_USERINFO, CacheMode.NO_CACHE,
                    new HttpParams("RequestMethod", "NickName"),
                    new HttpParams("UniqueId", uniqueId),
                    new HttpParams("NickName", etNickName.getText().toString().trim()));
        }
    }

    /**
     * 修改性别
     */
    private void btnEventChangeSex() {
        presenter.requestStrData(Interface.INTERFACE_CODE_Update_Sex, Interface.INTERFACE_USERINFO, CacheMode.NO_CACHE,
                new HttpParams("RequestMethod", "Sex"),
                new HttpParams("UniqueId", uniqueId),
                new HttpParams("Sex", String.valueOf(sex)));
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (group.getId() == rgSex.getId()) {
            if (checkedId == rbSexMale.getId()) {
                sex = 0;
            } else if (checkedId == rbSexFemale.getId()) {
                sex = 1;
            } else if (checkedId == rbSexNone.getId()) {
                sex = 2;
            }
        }
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        if (view.getId() == dpBirthday.getId()) {
            strBirthday = String.valueOf(year).concat("-").concat(String.valueOf(monthOfYear + 1)).concat("-").concat(String.valueOf(dayOfMonth));
            tvBirthday.setText(strBirthday);
        }
    }

    @Override
    public void showOnSuccess(int requestId, String responseBody, Response response) {
        if (requestId == Interface.INTERFACE_CODE_Update_NickName) {
            RootRes rootRes = gson.fromJson(responseBody, RootRes.class);
            ToastUtils.showShort(rootRes.getResultDes());
            if (rootRes.isResultStatus()) {
                LoginSpRes loginSpRes = AccountUtil.getStrLoginSp();
                if (loginSpRes != null) {
                    loginSpRes.setNickName((String) rootRes.getResultData());
                    AccountUtil.updateLoginSp(loginSpRes);
                    EventBusUtils.sendStickyEvent(new Event(EventBusCode.ChangeUserInfo_Refresh));
                }
            }
        } else if (requestId == Interface.INTERFACE_CODE_Update_Sex) {
            RootRes rootRes = gson.fromJson(responseBody, RootRes.class);
            ToastUtils.showShort(rootRes.getResultDes());
            if (rootRes.isResultStatus()) {
                LoginSpRes loginSpRes = AccountUtil.getStrLoginSp();
                if (loginSpRes != null) {
                    String tempSex = (String) rootRes.getResultData();
                    loginSpRes.setSex(Integer.parseInt(tempSex));
                    AccountUtil.updateLoginSp(loginSpRes);
                    EventBusUtils.sendStickyEvent(new Event(EventBusCode.ChangeUserInfo_Refresh));
                }
            }
        } else if (requestId == Interface.INTERFACE_CODE_Update_Birth) {
            RootRes rootRes = gson.fromJson(responseBody, RootRes.class);
            ToastUtils.showShort(rootRes.getResultDes());
            if (rootRes.isResultStatus()) {
                LoginSpRes loginSpRes = AccountUtil.getStrLoginSp();
                if (loginSpRes != null) {
                    loginSpRes.setBirthday((String) rootRes.getResultData());
                    AccountUtil.updateLoginSp(loginSpRes);
                    EventBusUtils.sendStickyEvent(new Event(EventBusCode.ChangeUserInfo_Refresh));
                }
            }
        }
    }
}
